<template>
  <div class='container'>
    <el-card class="app">
      <div class="title">
        {{$route.query.id?'试题修改':'试题录入'}}
         <el-divider></el-divider>
      </div>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
  <el-form-item label="学科:" prop="subjectID">
      <el-select v-model="ruleForm.subjectID" placeholder="请选择" style="width: 400px" @change="getDiscipline">
    <el-option
      v-for="item in disciplinelist"
      :key="item.value"
      :label="item.label"
      :value="item.value"
      >
    </el-option>
  </el-select>
  </el-form-item>
  <el-form-item label="目录:" prop="catalogID">
      <el-select v-model="ruleForm.catalogID" placeholder="请选择" style="width: 400px">
    <el-option
      v-for="item in directorylist"
      :key="item.value"
      :label="item.label"
      :value="item.value">
    </el-option>
  </el-select>
  </el-form-item>
  <!--  -->
    <el-form-item label="企业:" prop="enterpriseID">
      <el-select v-model="ruleForm.enterpriseID" placeholder="请选择" style="width: 400px">
    <el-option
      v-for="item in enterpriselist"
      :key="item.value"
      :label="item.shortName"
      :value="item.id">
    </el-option>
  </el-select>
  </el-form-item>
  <!--  -->
      <el-form-item label="城市:" prop="province">
      <el-select v-model="ruleForm.province" placeholder="请选择" style="width: 210px" @change="changecity">
    <el-option
      v-for="item in citys"
      :key="item"
      :label="item"
      :value="item">
    </el-option>
  </el-select>
        <el-select v-model="ruleForm.city" placeholder="请选择" style="width: 180px; margin-left: 10px">
    <el-option
      v-for="item in region"
      :key="item"
      :label="item"
      :value="item">
    </el-option>
  </el-select>
  </el-form-item>
  <!--  -->
      <el-form-item label="方向:" prop="direction">
      <el-select v-model="ruleForm.direction" placeholder="请选择" style="width: 400px">
    <el-option
      v-for="item in directions"
      :key="item"
      :label="item"
      :value="item">
    </el-option>
  </el-select>
  </el-form-item>
  <!--  -->
  <el-form-item label="题型:" prop="questionType">
    <el-radio-group v-model="ruleForm.questionType">
      <el-radio v-for="item in questionType" :key="item.value" :label="item.value+''">{{item.label}}</el-radio>
    </el-radio-group>
  </el-form-item>
  <!--  -->
    <el-form-item label="难度:" prop="difficulty">
    <el-radio-group v-model="ruleForm.difficulty">
      <el-radio v-for="item in difficulty" :key="item.value" :label="item.value+''">{{item.label}}</el-radio>
    </el-radio-group>
  </el-form-item>
  <!--  -->
      <el-form-item label="题干:" prop="question">
 <quill-editor  v-model="ruleForm.question" :options="editorOption" style="height:200px; margin-bottom: 40px; width: 100%" @blur="checkQustion"></quill-editor>
  </el-form-item>
  <!--  -->
    <el-form-item label="选项:" prop="options" v-if="ruleForm.questionType!=='3'">
    <div class="option_item" v-for="item in ruleForm.options" :key="item.code">
     <el-radio v-if="ruleForm.questionType==='1'" @change="changeRadio(item)" v-model="item.isRight" style="margin-right:0" :label="true">{{item.code}}：</el-radio>
     <!--  -->
     <el-checkbox v-if="ruleForm.questionType==='2'" v-model="item.isRight" style="margin-right:0" :label="true">{{item.code}}：</el-checkbox>
     <el-input v-model="item.title" style="width:240px; height: 50px"></el-input>
        <el-upload
      style="margin-left:4px"
      class="avatar-uploader"
      action="https://jsonplaceholder.typicode.com/posts/"
      :headers="{'Authorization':'Bearer '+ token}"
      :on-success="(res,file)=>{uploadSuccess(item,res,file)}"
      :show-file-list="false">
      <img v-if="item.img" :src="item.img" class="avatar">
      <span v-else>上传图片</span>
      <i class="el-icon-circle-close"></i>
    </el-upload>
    </div>
    <!--  -->
    <el-button type="danger" :disabled="ruleForm.questionType!=='2'" @click="addOption" size="small">+增加选项与答案</el-button>
  </el-form-item>
  <!--  -->
    <el-form-item label="解析视频:" prop="videoURL">
     <el-input style="width: 400px" v-model="ruleForm.videoURL"></el-input>
  </el-form-item>
  <!--  -->
      <el-form-item label="答案解析:" prop="question">
 <quill-editor ref="myTextEditor" v-model="ruleForm.answer" :options="editorOption" style="height:200px; margin-bottom: 40px; width: 100%"></quill-editor>
  </el-form-item>
  <!--  -->
  <el-form-item label="题目备注:" prop="remarks">
    <el-input type="textarea" v-model="ruleForm.remarks" style="width: 400px"></el-input>
  </el-form-item>
  <!--  -->
    <el-form-item label="试题标签:" prop="tags">
      <el-select v-model="ruleForm.tags" placeholder="请选择试题标签" style="width: 400px" multiple>
    <el-option
      v-for="item in tagslabel"
      :key="item.value"
      :label="item.label"
      :value="item.label"
      >
    </el-option>
  </el-select>
  </el-form-item>
  <el-form-item>
    <el-button v-if="!$route.query.id" type="primary" @click="submit()">确认提交</el-button>
    <el-button v-else type="success" @click="update()">确认修改</el-button>
  </el-form-item>
</el-form>
    </el-card>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { quillEditor } from 'vue-quill-editor'
import { simple as getsubSim } from '@/api/hmmm/subjects'
import { simple as getDirectorys } from '@/api/hmmm/directorys'
import { list as getEnterprise } from '@/api/hmmm/companys'
import { provinces, citys } from '@/api/hmmm/citys'
import { direction, questionType, difficulty } from '@/api/hmmm/constants'
import { getToken } from '@/utils/auth'
import { simple as getlabel } from '@/api/hmmm/tags'
import { add, detail, update } from '@/api/hmmm/questions'
export default {
  components: {
    quillEditor
  },
  data () {
    return {
      token: getToken(),
      // 学科
      disciplinelist: [],
      disciplineId: '',
      // 目录
      directorylist: [],
      // 企业
      enterpriselist: [],
      // 城市
      citys: provinces(),
      // 地区
      region: [],
      // 方向
      directions: direction,
      // 题型
      questionType,
      // 难度
      difficulty,
      // 标签
      tagslabel: [],
      // topic: '',
      // difficulty: '',
      editorOption: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['blockquote'],
            ['code-block', 'image', 'link']
          ]
          // 语法高亮
          // syntax: {
          //   highlight: text => hljs.highlightAuto(text).value
          // }
        }
      },
      // 试题对象
      ruleForm: {
        // 学科
        subjectID: null,
        // 目录
        catalogID: null,
        // 企业
        enterpriseID: null,
        // 城市
        province: null,
        // 地区
        city: null,
        // 方向
        direction: null,
        // 题型
        questionType: '1',
        // 难度
        difficulty: '1',
        // 题干
        question: null,
        // 标签
        tags: null,
        // 视频
        videoURL: '',
        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ],
        remarks: ''
      },
      // 校验
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择城市', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: 'change' }
        ],
        tags: [
          { required: true, message: '请输入标签', trigger: 'change' }
        ],
        desc: [
          { required: true, message: '请输入题目备注' }
        ],
        videoURL: [
          { required: true, message: '请输入视频地址', trigger: 'change' }
        ]
      }
    }
  },
  created () {
    this.getsubSim() // 学科
    // this.getDirectorys() // 目录
    this.getEnterprise()
    // this.getlabel() // 标签
    if (this.$route.query.id) {
      this.getQuestion()
    }
  },
  methods: {
    // 学科
    async getDiscipline () {
      // const res = await getsubSim()
      // console.log(res)
      // this.disciplinelist = res.data
      // this.disciplineId = this.ruleForm.discipline
      this.directorylist = null
      const res1 = await getDirectorys({ subjectID: this.ruleForm.subjectID })
      console.log(res1)
      this.directorylist = res1.data
      const res2 = await getlabel({ subjectID: this.ruleForm.subjectID })
      this.tagslabel = res2.data
    },
    async getsubSim () {
      const res = await getsubSim()
      this.disciplinelist = res.data
    },
    // 目录
    // async getdirectory () {
    //   const res = await getDirectorys({
    //     page: 1,
    //     pagesize: 30,
    //     subjectID: this.disciplineId
    //   })
    //   console.log(res)
    //   this.directorylist = res.data.items
    // },
    // 企业
    async getEnterprise () {
      const res = await getEnterprise()
      console.log(res)
      this.enterpriselist = res.data.items
    },
    // 地区
    changecity (cityName) {
      this.ruleForm.city = null
      this.region = citys(cityName)
    },
    changeRadio (item) {
      // 1. 清除所有的选中
      this.ruleForm.options.forEach(item => {
        item.isRight = false
      })
      // 2. 自己选中
      item.isRight = true
    },
    // 题干校验
    checkQustion () {
      this.$refs.ruleForm.validateField('question')
    },
    addOption () {
      // 规律：
      // 索引 0 ---> A  ascii  65
      // 索引 1 ---> B  ascii  66
      // 索引 2 ---> C  ascii  67
      // 索引 3 ---> D  ascii  68
      // 索引 4 ---> E  ascii  69
      this.ruleForm.options.push({
        isRight: false,
        code: String.fromCharCode(65 + this.ruleForm.options.length),
        title: '',
        img: ''
      })
    },
    // 图片
    uploadSuccess (item, res, file) {
      // res 是相应对象
      // file 选择后的文件对象   file.raw 原始文件对象
      // URL.createObjectURL(file.raw)  本地预览地址
      // item 就是当前的选项对象
      item.img = URL.createObjectURL(file.raw)
    },
    // 标签
    // async getlabel () {
    //   const res = await getlabel()
    //   console.log(res)
    //   this.tagslabel = res.data
    // },
    // 提交
    async submit () {
      try {
        await this.$refs.ruleForm.validate()
      } catch {
        return false
      }
      const data = { ...this.ruleForm }
      data.tags = data.tags.join(',')

      await add(data)
      this.$message.success('添加成功')
      this.$router.push('/questions/list')
    },
    // 回显
    async getQuestion () {
      const { data } = await detail({ id: this.$route.query.id })
      console.log(data)
      data.tags = data.tags.split(',')
      data.options = data.options.map(item => {
        item.isRight = item.isRight === 1
        return item
      })
      this.ruleForm = data
      const res = await getDirectorys({ subjectID: this.ruleForm.subjectID })
      this.directorylist = res.data
    },
    async update () {
      try {
        await this.$refs.ruleForm.validate()
      } catch {
        return false
      }
      const data = { ...this.ruleForm }
      console.log(typeof (data.remarks), 111)
      data.tags = data.tags.join(',')
      await update(data)
      this.$message.success('修改成功')
      // this.$router.push('/questions/list')
      this.$router.go(-1)
    }
  }
}
</script>

<style scoped lang='scss'>
.title {
  height: 60px;
}
.app {
  margin: 20px 30px 10px 20px;
}
.option_item{
  padding-bottom: 20px;
}
.avatar-uploader{
  display: inline-block;
  vertical-align: middle;
  line-height: 1;
}
.container ::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  width: 100px;
  height: 60px;
  line-height: 60px;
}
.avatar {
  width: 100px;
  height: 60px;
  display: block;
  overflow: hidden;
}
</style>
